'''
......
'''
import requests
import json
import time
import js_inject
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

site_url = "https://manatuku.com/payments/new"
captcha_task_url = "https://api.capsolver.com/createTask"
captcha_task_result = "https://api.capsolver.com/getTaskResult"

api_key = "CAP-147149A8FD7E82B0A83BCD2E317C51AB2D5060780317C5C0488E4DBBFF596609"

options = webdriver.ChromeOptions()
# options.add_argument('--proxy-server=http://127.0.0.1:7890')
options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
# options.add_argument('--lang=ja-JP')
options.add_argument("--start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--disable-blink-features=AutomationControlled")
service = Service(executable_path="E:\deleloptool\chromedriver-win64\chromedriver.exe")
options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})
driver = webdriver.Chrome(options=options, service=service)


def create_task(website_url, context, iv, challenge_script_url, web_key):
    proxies = {'https': 'http://127.0.0.1:7897'}
    query = {
        "clientKey": api_key,
        "task": {
            "type": "AntiAwsWafTask",
            "websiteURL": "https//manatuku.com",
            "awsIv": iv,
            "awsContext": context,
            "awsKey": web_key,
            "awsChallengeJS":  challenge_script_url
        }
    }

    res = requests.post(captcha_task_url, json=query,proxies=proxies,verify=False,timeout=5)
    resp = res.json()
    task_id = resp.get("taskId")
    return task_id


def get_task_result(task_id):
    print("获取任务结果中...")
    proxies = {'https': 'http://127.0.0.1:7897'}
    result_data = {"clientKey": api_key, "taskId": task_id}
    while True:
        response = requests.post(captcha_task_result, json=result_data,proxies=proxies,verify=False,timeout=5)
        resp = response.json()
        status = resp.get("status")
        if status == "ready":
            return resp.get("solution", {}).get('cookie')
        if status == "failed" or resp.get("errorId"):
            print("Solve failed! response:", response.text)
            return None

def capsolver():
    print("打开页面中...")
    driver.get('https://manatuku.com/payments/new')

    # 等待页面完全加载
    WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("return document.readyState") == "complete"
    )

    # 等待gokuProps定义
    WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("return typeof window.gokuProps !== 'undefined'")
    )

    captcha_params = driver.execute_script(js_inject.challenge_js)
    if captcha_params:
        print("网站密钥:", captcha_params['websiteKey'])
        print("上下文:", captcha_params['context'])
        print("IV:", captcha_params['iv'])
        print("挑战脚本:", captcha_params['challengeScriptUrl'])
        print("验证码脚本:", captcha_params['captchaScriptUrl'])

    website_key = captcha_params['websiteKey']
    context = captcha_params['context']
    iv = captcha_params['iv']
    challenge_script_url = captcha_params['challengeScriptUrl']
    #captcha_script_url = challenge_script_url.replace('challenge.js', 'captcha.js').replace('token', 'captcha')

    wait = WebDriverWait(driver, 10)
    # clear_api_responses(driver)
    time.sleep(2)
    driver.execute_script(js_inject.intercept_script_improved)
    captcha_frame = wait.until(
        EC.presence_of_element_located((By.ID, "amzn-captcha-verify-button"))
    )
    captcha_frame.click()
    time.sleep(3)
    # responses = get_api_responses(driver,method_filter="get")
    responses = driver.execute_script(js_inject.get_urls_script)
    print(responses)
    if responses:
        website_url = [r for r in responses if 'captcha.awswaf.com' in r]
        task_id = create_task(website_url[0],context,iv,challenge_script_url,website_key)
        if  task_id:
            result = get_task_result(task_id)
            if result:
                print("<UNK>:", result)


if __name__ == '__main__':
    capsolver()